﻿using Kinlo.Entitys;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using UIWindows.GlobalStatics;
using UIWindows.Services.Context;
using UIWindows.Tools.Helper;
using XingLucifer.Devices;
using XingLucifer.Devices.Models;
using XingLucifer.IBase.Enums;

namespace UIWindows.Services.Handle
{
    [Attributes.TaskClass(TaskTypes.绝缘测试)]
    public class RJ6901A_InsulationuplimitHandle : ServierBase
    {
        public RJ6901A_InsulationuplimitHandle(DeviceConfigStatic deviceConfig, SystemConfigStatic systemConfig,
            UserConfigStatic userConfig, ParameterStatic parameterStatic, TemporaryStatic temporaryStatic, HomeStatic homeStatic, MesParameterStatic mesParameterStatic)
            : base(deviceConfig, systemConfig, userConfig, parameterStatic, temporaryStatic, homeStatic, mesParameterStatic)
        {

        }

        private volatile int _ngInsulation = 0;
        public override Task Handle(DataContext context)
        {
            try
            {
                if (!ClearSignal(context)) { return Task.CompletedTask; }
                _ngInsulation = 0;
                var plc = _deviceConfig.DeviceList.FirstOrDefault(x => x.ServiceName == context.ServiceName && x.TaskType == TaskTypes.扫描信号).Communication as OmronCIP;
                DateTime weighing_time = DateTime.Now;
                var erinnerungen = ReadErinnerungen(plc, context.Address_Struct, context.Struct_Length, _systemConfig.IAddress.Erinnerungen_Kurzschluss, context.AddressingMethod);
                if (erinnerungen.Item1)
                {
                    $"==>>{context.TaskType}<<==\r\n收到启动信号，没收到电池记忆，请联系电气工程师！！！".MessageDialogs(MessageLevelType.错误, false, Enums.PopUpTypes.Global);
                    return base.Handle(context);
                }
                RunLog($"记忆ID：{string.Join(";", erinnerungen.Item2.Select(x => x.SnowflakeId))}");
                Parallel.ForEach(erinnerungen.Item2, battery =>
                {
                    RunLog($"进入绝缘测试工序：{battery.SnowflakeId}");
                    if (battery.SnowflakeId == 0) { return; }
                    Models.Devices.DeviceClientModel? device = _deviceConfig.DeviceList.FirstOrDefault(x => x.ServiceName == context.ServiceName && x.TaskType == context.TaskType
                    && x.DeviceType == context.DeviceType && x.Index == battery.Index);
                    if (device == null)
                    {
                        RunLog($"找不到[{battery.Index}]号设备", MessageLevelType.错误);
                        return;
                    }
                    RJ6901AResultModel rJ6901AResult = null;
                    try
                    {
                        RunLog($"-[{battery.Index}] 开始检测");
                        string status = string.Empty;
                        rJ6901AResult = device.Communication.ReadClass<RJ6901AResultModel>(2);

                        $"-[{battery.Index}] 获取结果原始值：{rJ6901AResult.TestMsg}".RunLog(MessageLevelType.信息);
                    }
                    catch (Exception ex)
                    {
                        $"-[{battery.Index}] 获取结果时发生异常：{ex.ToString().Trim()}".RunLog(MessageLevelType.警告);
                    }
                    if (battery.SnowflakeId == -1)
                    {
                        RunLog($"-[{battery.Index}] 绝缘测试点检 地址：{battery.Address_Struct}");
                        WriteResult("", rJ6901AResult == null ? ResultTypes.不合格 : ResultTypes.合格, plc, battery.Address_Struct, context);
                        return;
                    }
                    if (rJ6901AResult == null)
                    {
                        $"-[{battery.Index}] 采集数据异常".RunLog(MessageLevelType.警告);
                        WriteResult("", ResultTypes.不合格, plc, battery.Address_Struct, context);
                        return;
                    }
                    DateTime dateTime = DateTime.Now;
                    ProductionData? entity = _temporaryStatic.EntityCache.FirstOrDefault(x => x.SnowflakeId == battery.SnowflakeId);
                    if (entity == null)
                    {
                        RunLog($"-[{battery.Index}] 实体缓存查询不到==>[{battery.SnowflakeId}]，转到数据库查询");
                        entity = dateTime.GetEntity(context.TaskType, battery.SnowflakeId, DBSuffix);
                    }
                    else
                    {
                        ProductionData.Meta.TableName = entity.Items["TableName"].ToString();
                    }
                    if (entity == null)
                    {
                        RunLog($"-[{battery.Index}] 数据库找不到ID为：{battery.SnowflakeId}");
                        WriteResult("", ResultTypes.数据库找不到电池, plc, battery.Address_Struct, context);
                        return;
                    }
                    RunLog($"-[{battery.Index}] ID：[{battery.SnowflakeId}] 条码：[{entity.BarCode}]");
                    RunLog($"-[{battery.Index}] ID：[{battery.SnowflakeId}] 条码：[{entity.BarCode}]\r\n 绝缘测试数据：{System.Text.Json.JsonSerializer.Serialize(rJ6901AResult, GlobalStatic.Options)}");
                    //entity.LocationShortCircuitTester = battery.Index;
                    entity.TimeInsulation = dateTime.GetJSTimeUtc();
                    entity.InsulationElectricCurrent = rJ6901AResult.电流参数;
                    entity.InsulationResistance = rJ6901AResult.电阻参数;
                    entity.InsulationVoltage = rJ6901AResult.返回电压参数;
                    entity.InsulationTestTime = rJ6901AResult.测试时间;
                    entity.InsulationResidueTime = rJ6901AResult.时间;


                    entity.InsulationResistanceUp  = rJ6901AResult.阻值上限值;
                    entity.InsulationResistanceDown = rJ6901AResult.阻值下限值;


                    if (rJ6901AResult.结果 == 1)
                    {
                        entity.ResultInsulation = ResultTypes.合格;
                        //Interlocked.Increment(ref _okShortCircuit);
                    }
                    else
                    {
                        entity.ResultInsulation = ResultTypes.绝缘测试NG;
                        Interlocked.Increment(ref _ngInsulation);
                    }

                    if (entity.ResultTotal==ResultTypes._)
                        entity.ResultTotal = entity.ResultInsulation;
                    else if (entity.ResultInsulation == ResultTypes.合格 &&
                    (entity.ResultTotal == ResultTypes.绝缘测试NG))
                    {
                        entity.ResultTotal = entity.ResultShortCicute;
                    }
                    try
                    {
                        entity.Update();
                        _homeStatic.AddShortCircuitBattery(entity.BarCode, entity,2);
                    }
                    catch (Exception ex)
                    {
                        //RunLog($"-[{battery.Index}] [{(battery.Data_PLC == 1 ? "电极" : "壳体")}] 更新数据异常：{ex}");
                        RunLog($"-[{battery.Index}] [{("绝缘测试")}] 更新数据异常：{ex}");
                    }
                    if (_parameterStatic.DecideParameter.EnableEmptyRun)
                    {
                        RunLog($"-[{battery.Index}] 启用空跑模式==>{entity.BarCode} 强制合格");
                        entity.ResultTotal = ResultTypes._;
                    }
                    WriteResult(entity.BarCode, entity.ResultTotal != ResultTypes._ ? entity.ResultTotal : ResultTypes.合格, plc, battery.Address_Struct, context);
                });
                _homeStatic.ChartData.NG_Insulation += _ngInsulation;
                return base.Handle(context);
            }
            catch (Exception ex)
            {
                RunLog($"任务异常==>{ex}");
            }
            return Task.CompletedTask;
        }

        private bool RangeCheck(double value, string range)
        {
            string[] str = range.Split('=');
            double up = double.Parse(str[0]);
            double down = double.Parse(str[1]);
            return value <= up && value >= down;
        }

        private bool Cmd_Execute(byte[] cmd, Models.Devices.DeviceClientModel com, int index, string cmd_name, Func<string, bool> condition)
        {
            com.Communication.WriteSingle(cmd, 0, 0, 0);
            Thread.Sleep(50);
            byte[] bytes = com.Communication.ReadSingle<byte[]>(0, 0);
            if (bytes != null)
            {
                RunLog($"-[{index}] {cmd_name} 仪器返回：{BitConverter.ToString(bytes)}");
            }
            return false;
        }
    }
}
